using UnityEngine;
using UnityEngine.UI;
using System.Collections;
using Unity.VisualScripting;

public class AlphaButtonClickMask : MonoBehaviour, ICanvasRaycastFilter
{
    protected PolygonUIMesh _image;
    private Color _color;
    private RectTransform recttf;
    // Texture2D t2d;

    public void Start()
    {
        _image = GetComponent<PolygonUIMesh>();
        recttf = transform as RectTransform;
        _color = _image.color;
        // t2d = _color.GetPixel();
    }

    public bool IsRaycastLocationValid(Vector2 sp, Camera eventCamera)
    {
        Vector2 localPoint;
        RectTransformUtility.ScreenPointToLocalPointInRectangle(_image.rectTransform, sp, eventCamera, out localPoint);

        //判断几何
        return IsPointInPolygon(localPoint);

        //判断三角形
        return IsPointInTriangle(localPoint,
            transform.GetChild(0).localPosition,
            transform.GetChild(1).localPosition,
            transform.GetChild(2).localPosition);
    }


    private bool IsPointInTriangle(Vector3 point, Vector3 vertex1, Vector3 vertex2, Vector3 vertex3)
    {
        Vector3 AB = vertex2 - vertex1;
        Vector3 BC = vertex3 - vertex2;
        Vector3 CA = vertex1 - vertex3;

        Vector3 AP = point - vertex1;
        Vector3 BP = point - vertex2;
        Vector3 CP = point - vertex3;

        Vector3 crossABP = Vector3.Cross(AB, AP);
        Vector3 crossBCP = Vector3.Cross(BC, BP);
        Vector3 crossCAP = Vector3.Cross(CA, CP);

        bool isInside = Vector3.Dot(crossABP, crossBCP) >= 0f && Vector3.Dot(crossBCP, crossCAP) >= 0f;

        return isInside;
    }

    //多边形
    private bool IsPointInPolygon(Vector2 p)
    {
        int intersectCount = 0;
        int length = transform.childCount;

        for (int i = 0, j = length - 1; i < length; j = i++)
        {
            var tf = transform.GetChild(i);
            var tf1 = transform.GetChild(j);
            Vector2 v1 = new Vector2(tf.localPosition.x, tf.localPosition.y);
            Vector2 v2 = new Vector2(tf1.localPosition.x, tf1.localPosition.y);

            if ((v1.y > p.y) != (v2.y > p.y) &&
                p.x < (v2.x - v1.x) * (p.y - v1.y) / (v2.y - v1.y) + v1.x)
            {
                intersectCount++;
            }
        }

        return intersectCount % 2 == 1;
    }
}